
<template>
  <div class="group-tour-detail">
    <div class="post-container">
      <!-- 顶部标题 -->
      <div class="post-header">
        <h2>编辑跟团游</h2>
        <div class="header-actions">
          <el-button type="text" @click="cancelForm">返回</el-button>
          <el-button type="primary" round @click="saveForm">保存修改</el-button>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="post-content">
        <!-- 表单区域 -->
        <div class="form-section">
          <!-- 标题和内容 -->
          <div class="form-group">
            <el-input
              v-model="form.group_tour_introduction"
              placeholder="输入正文标题"
              class="title-input"
              maxlength="30"
              show-word-limit
            />
            <div class="word-count">{{ form.group_tour_introduction.length }}/30</div>
          </div>

          <div class="form-group content-box">
            <div ref="editorContainer" class="quill-editor" />
          </div>

          <!-- 基本信息卡片 -->
          <div class="info-card">
            <div class="card-header">
              <h3>基本信息</h3>
              <el-button type="text" @click="toggleCard('basic')">
                {{ expandedCards.basic ? '收起' : '展开' }}
              </el-button>
            </div>
            <div v-show="expandedCards.basic" class="card-content">
              <div class="two-column-form">
                <div class="column">
                  <el-form-item label="跟团游状态">
                    <el-select
                      v-model="form.progress_status"
                      placeholder="请选择状态"
                      style="width: 300px"
                      :disabled="isProgressStatusDisabled"
                    >
                      <el-option label="未开始" value="未开始" />
                      <el-option label="报名中" value="报名中" />
                      <el-option label="报名截止" value="报名截止" />
                      <el-option label="进行中" value="进行中" />
                      <el-option label="已结束" value="已结束" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="到达景点">
                    <el-select
                      v-model="form.scenic_spot_id"
                      filterable
                      placeholder="请选择景点"
                      style="width: 300px"
                      @change="handleScenicSpotChange"
                    >
                      <el-option
                        v-for="spot in scenicSpots"
                        :key="spot.scenicSpotId"
                        :label="spot.scenicAreaName"
                        :value="spot.scenicSpotId"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="省份">
                    <el-select 
                      v-model="form.province" 
                      filterable 
                      placeholder="请选择省份" 
                      style="width: 300px"
                      @change="handleProvinceChange"
                    >
                      <el-option 
                        v-for="item in provinceOptions" 
                        :key="item" 
                        :label="item" 
                        :value="item" 
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="城市">
                    <el-select 
                      v-model="form.city" 
                      filterable 
                      placeholder="请选择城市" 
                      style="width: 300px"
                    >
                      <el-option 
                        v-for="item in cityOptions" 
                        :key="item" 
                        :label="item" 
                        :value="item" 
                      />
                    </el-select>
                  </el-form-item>
                </div>
                <div class="column">
                  <el-form-item label="出发日期">
                    <el-date-picker
                      v-model="form.start_date"
                      type="date"
                      placeholder="选择日期"
                      value-format="YYYY-MM-DD"
                      style="width: 300px"
                    />
                  </el-form-item>
                  <el-form-item label="结束日期">
                    <el-date-picker
                      v-model="form.end_date"
                      type="date"
                      placeholder="选择日期"
                      value-format="YYYY-MM-DD"
                      style="width: 300px"
                    />
                  </el-form-item>
                  <el-form-item label="集合时间">
                    <el-time-picker
                      v-model="form.assembly_time"
                      placeholder="选择时间"
                      value-format="HH:mm:ss"
                      style="width: 300px"
                    />
                  </el-form-item>
                  <el-form-item label="集合地点">
                    <el-input 
                      v-model="form.assembly_place" 
                      placeholder="请输入集合地点" 
                      style="width: 300px"
                    />
                  </el-form-item>
                </div>
              </div>
            </div>
          </div>

          <!-- 价格信息卡片 -->
          <div class="info-card">
            <div class="card-header">
              <h3>价格信息</h3>
              <el-button type="text" @click="toggleCard('price')">
                {{ expandedCards.price ? '收起' : '展开' }}
              </el-button>
            </div>
            <div v-show="expandedCards.price" class="card-content">
              <el-form label-width="100px" class="inline-form">
                <el-form-item label="团费价格">
                  <el-input-number
                    v-model="form.group_tour_price"
                    :min="0"
                    :precision="2"
                    controls-position="right"
                    style="width: 200px"
                  >
                    <template #prefix>¥</template>
                  </el-input-number>
                </el-form-item>
                <el-form-item label="招募人数" class="recruitment-item">
                  <el-input-number
                    v-model="form.recruitment_number"
                    :min="1"
                    :max="100"
                    controls-position="right"
                    style="width: 200px"
                  />
                </el-form-item>
              </el-form>
            </div>
          </div>

          <!-- 负责人信息卡片 -->
          <div class="info-card">
            <div class="card-header">
              <h3>负责人信息</h3>
              <el-button type="text" @click="toggleCard('contact')">
                {{ expandedCards.contact ? '收起' : '展开' }}
              </el-button>
            </div>
            <div v-show="expandedCards.contact" class="card-content">
              <el-form label-width="100px">
                <el-form-item label="负责人姓名">
                  <el-input 
                    v-model="form.principal_name" 
                    placeholder="请输入负责人姓名" 
                    style="width: 300px"
                  />
                </el-form-item>
                <el-form-item label="联系电话">
                  <el-input 
                    v-model="form.principal_phone" 
                    placeholder="请输入联系电话" 
                    style="width: 300px"
                  />
                </el-form-item>
                <el-form-item label="电子邮箱">
                  <el-input 
                    v-model="form.principal_email" 
                    placeholder="请输入电子邮箱" 
                    style="width: 300px"
                  />
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>

        <!-- 图片上传区域 -->
        <div class="upload-section">
          <div class="upload-title">
            <span>图片编辑</span>
            <span class="count">{{ groupTourImages.length }}/6</span>
          </div>
          <div class="image-grid">
            <!-- 已上传的图片 -->
            <div v-for="(img, index) in groupTourImages" :key="index" class="grid-item">
              <el-image 
                :src="img.groupTourImageLink" 
                :preview-src-list="groupTourImages.map(i => i.groupTourImageLink)" 
                fit="cover" 
                class="grid-image" 
              />
              <el-button 
                class="delete-btn" 
                type="danger" 
                :icon="Close" 
                circle 
                size="small"
                @click.stop="handleDeleteImage(img.groupTourImageId)"
              />
            </div>

            <!-- 上传按钮 -->
            <div v-for="i in 6 - groupTourImages.length" :key="'empty-' + i" class="grid-item empty-placeholder">
              <el-upload 
                class="plus-upload" 
                action="#" 
                :show-file-list="false" 
                :http-request="handleUploadImage"
                :before-upload="beforeUpload"
              >
                <el-icon class="placeholder-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </div>
          </div>
        </div>
        
        <!-- 报名信息区域 - 移动到post-content内部最后 -->
        <div class="registration-section" v-if="groupTourId">
          <div class="section-header">
            <h3>报名信息</h3>
            <el-button 
              type="primary" 
              size="small" 
              @click="loadRegistrations"
              :loading="loadingRegistrations"
            >
              刷新报名列表
            </el-button>
          </div>
          <el-table 
            :data="registrations" 
            border 
            style="width: 100%"
            v-loading="loadingRegistrations"
          >
            <el-table-column prop="userName" label="用户姓名" width="120" />
            <el-table-column prop="userPhone" label="联系电话" width="150" />
            <el-table-column prop="transactionAmount" label="交易金额" width="120">
              <template #default="{row}">
                ¥{{ row.transactionAmount }}
              </template>
            </el-table-column>
            <el-table-column prop="registrationTime" label="报名时间" width="180" />
            <el-table-column label="操作" width="120">
              <template #default="{row}">
                <el-button 
                  type="text" 
                  size="small"
                  @click="viewRegistrationDetail(row.registrationId)"
                >
                  查看用户
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 保存成功弹窗 -->
    <el-dialog
      v-model="saveDialogVisible"
      title="保存成功"
      width="400px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content">
        <el-icon color="#67C23A" :size="60"><CircleCheck /></el-icon>
        <p class="dialog-message">跟团游信息已成功更新！</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="handleSaveDialogClose">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { Plus, CircleCheck, Close } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'
import Quill from 'quill'
import 'quill/dist/quill.snow.css'

const editorContainer = ref(null)
let quillInstance = null
const router = useRouter()
const route = useRoute()

const isProgressStatusDisabled = computed(() => {
  return form.value.audit_status !== '通过'
})

// 计算属性 - 当前景点名称
const currentScenicSpotName = computed(() => {
  if (!form.value.scenic_spot_id) return form.value.scenic_spot_name || ''
  const spot = scenicSpots.value.find(s => s.scenicSpotId === form.value.scenic_spot_id)
  return spot ? spot.scenicAreaName : form.value.scenic_spot_name || ''
})

// 初始化富文本编辑器
const initEditor = () => {
  quillInstance = new Quill(editorContainer.value, {
    theme: 'snow',
    placeholder: '请详细描述行程安排、特色亮点等信息...',
    modules: {
      toolbar: {
        container: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ header: 1 }, { header: 2 }],
          [{ list: 'ordered' }, { list: 'bullet' }],
          [{ script: 'sub' }, { script: 'super' }],
          [{ indent: '-1' }, { indent: '+1' }],
          [{ direction: 'rtl' }],
          [{ size: ['small', false, 'large', 'huge'] }],
          [{ header: [1, 2, 3, 4, 5, 6, false] }],
          [{ color: [] }, { background: [] }],
          [{ font: [] }],
          [{ align: [] }],
          ['clean'],
          ['image']
        ],
        handlers: {
          image: handleImageUpload
        }
      }
    }
  })

  quillInstance.on('text-change', () => {
    form.value.detail_content = quillInstance.root.innerHTML
  })
}

const handleImageUpload = () => {
  const input = document.createElement('input')
  input.setAttribute('type', 'file')
  input.setAttribute('accept', 'image/*')
  input.click()

  input.onchange = async () => {
    const file = input.files[0]
    if (!file) return

    const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
    if (!validTypes.includes(file.type)) {
      ElMessage.error('只支持上传 JPG/PNG/GIF/WEBP 格式的图片')
      return
    }

    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过5MB')
      return
    }

    const formData = new FormData()
    formData.append('file', file)

    try {
      const res = await axios({
        url: '/strategy/image/upload-image',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      if (res.data && res.data.url) {
        let imageUrl = res.data.url
        if (!imageUrl.startsWith('http')) {
          const baseUrl = 'http://localhost:8080'
          imageUrl = baseUrl + imageUrl
        }

        const range = quillInstance.getSelection()
        quillInstance.insertEmbed(range.index, 'image', imageUrl)
        ElMessage.success('图片上传成功')
      } else {
        ElMessage.error('图片上传失败: 未获取到图片URL')
      }
    } catch (err) {
      console.error('上传错误:', err)
      ElMessage.error(err.response?.data?.message || '图片上传失败')
    }
  }
}

// 表单数据
const form = ref({
  group_tour_id: null,
  group_tour_introduction: '',
  detail_content: '',
  scenic_spot_id: null,
  scenic_spot_name: '',
  province: '',
  city: '',
  region_id: null,
  principal_name: '',
  principal_phone: '',
  principal_email: '',
  start_date: '',
  end_date: '',
  assembly_time: '',
  assembly_place: '',
  recruitment_number: 20,
  group_tour_price: 0,
  travel_agency_id: null,
  audit_status: '未审核',
  progress_status: '未开始'  // 默认值为'未开始'
})

const groupTourImages = ref([])
const scenicSpots = ref([])
const provinceOptions = ref([])
const cityOptions = ref([])
const regionMap = ref({})
const expandedCards = ref({
  basic: true,
  price: true,
  contact: true
})
const saveDialogVisible = ref(false)
const loading = ref(false)

// 加载地区选项
const loadRegionOptions = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/regions')
    const regions = response.data || []
    provinceOptions.value = [...new Set(regions.map(r => r.province))]
    regionMap.value = {}
    regions.forEach(r => {
      if (!regionMap.value[r.province]) regionMap.value[r.province] = []
      regionMap.value[r.province].push(r.city)
    })
  } catch (error) {
    console.error('加载地区选项失败:', error)
  }
}

// 加载景点列表
const loadScenicSpots = async () => {
  try {
    const response = await axios.get('http://localhost:8080/mw/ScenicSpotList')
    scenicSpots.value = response.data || []
  } catch (error) {
    console.error('加载景点列表失败:', error)
  }
}

// 省份变化处理
const handleProvinceChange = (val) => {
  cityOptions.value = regionMap.value[val] || []
  if (!cityOptions.value.includes(form.value.city)) {
    form.value.city = ''
  }
}

// 选择景点时自动带出省份和城市
const handleScenicSpotChange = async (scenicSpotId) => {
  const spot = scenicSpots.value.find(s => s.scenicSpotId === scenicSpotId)
  if (spot) {
    form.value.scenic_spot_id = scenicSpotId
    form.value.scenic_spot_name = spot.scenicAreaName
    
    if (spot.regionId) {
      try {
        const regionResponse = await axios.get('http://localhost:8080/api/regions')
        const regions = regionResponse.data || []
        const region = regions.find(r => r.regionID === spot.regionId)
        if (region) {
          form.value.province = region.province
          form.value.city = region.city
          cityOptions.value = regionMap.value[region.province] || []
        }
      } catch (error) {
        console.error('获取地区信息失败:', error)
      }
    } else {
      form.value.province = ''
      form.value.city = ''
      cityOptions.value = []
    }
  } else {
    form.value.scenic_spot_id = null
    form.value.scenic_spot_name = ''
    form.value.province = ''
    form.value.city = ''
    cityOptions.value = []
  }
}

// 加载跟团游图片
const loadGroupTourImages = async (groupId) => {
  if (!groupId) return
  try {
    const response = await axios.get(`http://localhost:8080/mw/travelAuditImages/${groupId}`)
    groupTourImages.value = response.data || []
  } catch (error) {
    console.error('加载跟团游图片失败:', error)
    ElMessage.error('加载图片失败')
  }
}

// 上传前检查
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB！')
    return false
  }
  return true
}

// 上传图片
const handleUploadImage = async (options) => {
  const { file } = options
  if (!form.value.group_tour_id) {
    ElMessage.error('请先保存基本信息再上传图片')
    return
  }
  
  // 生成小于2147483647的随机ID
  const groupTourImageId = Math.floor(Math.random() * 1000000) + 1
  
  const formData = new FormData()
  formData.append('file', file)
  formData.append('groupTourId', form.value.group_tour_id.toString())
  formData.append('groupTourImageId', groupTourImageId.toString())

  try {
    const response = await axios.post('http://localhost:8080/mw/uploadGroupTourImage', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.data.success) {
      ElMessage.success('图片上传成功')
      await loadGroupTourImages(form.value.group_tour_id)
    } else {
      ElMessage.error(response.data.message || '图片上传失败')
    }
  } catch (error) {
    console.error('上传图片失败:', error)
    ElMessage.error('图片上传失败: ' + (error.response?.data?.message || error.message))
  }
}
// 删除图片
const handleDeleteImage = async (imageId) => {
  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete(`http://localhost:8080/mw/travelAuditImages/${imageId}`)
    if (response.data.success) {
      ElMessage.success('图片删除成功')
      await loadGroupTourImages(form.value.group_tour_id)
    } else {
      ElMessage.error(response.data.message || '图片删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除图片失败:', error)
      ElMessage.error('删除图片失败')
    }
  }
}

const toggleCard = (card) => {
  expandedCards.value[card] = !expandedCards.value[card]
}

// 获取当前旅行社ID
const getTravelAgencyId = async () => {
  const loginId = localStorage.getItem('loginId')
  if (!loginId) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  
  try {
    const response = await axios.get(`http://localhost:8080/mw/travelAgency/byLoginId/${loginId}`)
    if (response.data) {
      form.value.travel_agency_id = response.data.travelAgencyId
      localStorage.setItem('travelAgencyId', response.data.travelAgencyId)
    }
  } catch (error) {
    console.error('获取旅行社ID失败:', error)
    ElMessage.error('获取旅行社信息失败')
  }
}

// 加载跟团游详情
const loadGroupTourDetail = async (id) => {
  loading.value = true
  try {
    await loadScenicSpots()
    
    const response = await axios.get(`http://localhost:8080/mw/travelAuditDetail/${id}`)
    const data = response.data
    
    if (data) {
      form.value.group_tour_id = data.groupTourId
      form.value.group_tour_introduction = data.groupTourName
      form.value.scenic_spot_name = data.scenicAreaName || ''
      
      if (data.scenicSpotId) {
        form.value.scenic_spot_id = data.scenicSpotId
        await handleScenicSpotChange(data.scenicSpotId)
      } else if (data.scenicAreaName) {
        const spot = scenicSpots.value.find(s => s.scenicAreaName === data.scenicAreaName)
        if (spot) {
          form.value.scenic_spot_id = spot.scenicSpotId
          await handleScenicSpotChange(spot.scenicSpotId)
        }
      }
      
      if (data.province) {
        form.value.province = data.province
        cityOptions.value = regionMap.value[data.province] || []
      }
      if (data.city) {
        form.value.city = data.city
      }
      
      form.value.principal_name = data.principalName
      form.value.principal_phone = data.principalPhone
      form.value.principal_email = data.principalEmail
      form.value.start_date = data.startDate
      form.value.end_date = data.endDate
      form.value.assembly_time = data.assemblyTime
      form.value.assembly_place = data.assemblyPlace
      form.value.recruitment_number = data.recruitmentNumber
      form.value.group_tour_price = data.groupTourPrice
      form.value.detail_content = data.groupTourIntroduction
      form.value.travel_agency_id = data.travelAgencyId
      form.value.audit_status = data.auditStatus
      form.value.progress_status = data.progressStatus || '未开始'  // 确保正确设置状态
      
      if (quillInstance && data.groupTourIntroduction) {
        quillInstance.root.innerHTML = data.groupTourIntroduction
      }
      
      await loadGroupTourImages(id)
    }
  } catch (error) {
    console.error('加载跟团游详情失败:', error)
    ElMessage.error('加载跟团游详情失败')
  } finally {
    loading.value = false
  }
}

// 保存表单
const saveForm = async () => {
  const errors = []
  if (!form.value.group_tour_introduction.trim()) {
    errors.push('请输入正文标题')
  }
  if (!form.value.detail_content.trim() || form.value.detail_content === '<p><br></p>') {
    errors.push('请输入详细内容')
  }
  if (!form.value.scenic_spot_id && !form.value.scenic_spot_name) {
    errors.push('请选择景点或输入景点名称')
  }
  if (!form.value.province || !form.value.city) {
    errors.push('请选择省份和城市')
  }
  if (!form.value.start_date || !form.value.end_date) {
    errors.push('请选择出发和结束日期')
  }
  if (new Date(form.value.start_date) > new Date(form.value.end_date)) {
    errors.push('结束日期不能早于出发日期')
  }
  if (!form.value.assembly_time) {
    errors.push('请选择集合时间')
  }
  if (!form.value.assembly_place) {
    errors.push('请输入集合地点')
  }
  if (!form.value.principal_name) {
    errors.push('请输入负责人姓名')
  }
  if (!form.value.principal_phone) {
    errors.push('请输入联系电话')
  }
  if (!form.value.progress_status) {  // 新增状态验证
    errors.push('请选择跟团游状态')
  }
  
  if (errors.length > 0) {
    ElMessage.error(errors.join('，'))
    return
  }

  try {
    const regionResponse = await axios.get('http://localhost:8080/api/regions')
    const regions = regionResponse.data || []
    const region = regions.find(r => r.province === form.value.province && r.city === form.value.city)
    if (!region) {
      ElMessage.error('请选择有效的省份和城市')
      return
    }
    form.value.region_id = region.regionID
  } catch (error) {
    console.error('获取地区ID失败:', error)
    ElMessage.error('获取地区信息失败')
    return
  }

  const submitData = {
    groupTourId: form.value.group_tour_id,
    groupTourName: form.value.group_tour_introduction,
    travelAgencyId: form.value.travel_agency_id,
    scenicSpotId: form.value.scenic_spot_id,
    scenicAreaName: currentScenicSpotName.value,
    regionId: form.value.region_id,
    principalName: form.value.principal_name,
    principalPhone: form.value.principal_phone,
    principalEmail: form.value.principal_email,
    startDate: form.value.start_date,
    endDate: form.value.end_date,
    assemblyTime: form.value.assembly_time,
    assemblyPlace: form.value.assembly_place,
    recruitmentNumber: form.value.recruitment_number,
    groupTourPrice: form.value.group_tour_price,
    groupTourIntroduction: form.value.detail_content,
    auditStatus: form.value.audit_status,
    progressStatus: form.value.progress_status  // 确保包含进度状态
  }

  try {
    const response = await axios.put(
  `http://localhost:8080/mw/updateGroupTour/${form.value.group_tour_id}`, 
  submitData
)
    if (response.data) {
      saveDialogVisible.value = true
      ElMessage.success('跟团游信息更新成功')
      await loadGroupTourDetail(form.value.group_tour_id)
    }
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error(`更新失败: ${error.response?.data?.message || error.message}`)
  }
}

const handleSaveDialogClose = () => {
  saveDialogVisible.value = false
}

const cancelForm = () => {
  ElMessageBox.confirm('确定要取消编辑吗？所有未保存的修改将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/agencyframe/grouptoursend')
  }).catch(() => {
    // 用户点击了取消，不做任何操作
  })
}

const registrations = ref([])
const loadingRegistrations = ref(false)
const groupTourId = ref(null)

// 加载报名信息
const loadRegistrations = async () => {
  if (!groupTourId.value) return
  
  try {
    loadingRegistrations.value = true
    const response = await axios.get(`http://localhost:8080/gtr/byGroupTourId?groupTourId=${groupTourId.value}`)
    registrations.value = response.data || []
  } catch (error) {
    console.error('加载报名信息失败:', error)
    ElMessage.error('加载报名信息失败')
  } finally {
    loadingRegistrations.value = false
  }
}

// 查看报名详情
const viewRegistrationDetail = (registrationId) => {
  console.log('查看报名详情:', registrationId)
}

onMounted(() => {
  loadRegionOptions()
  loadScenicSpots()
  getTravelAgencyId()
  initEditor()
  
  const id = route.params.id
  if (id) {
    groupTourId.value = id
    loadGroupTourDetail(id)
    loadRegistrations()
  }
})

watch(() => route.params.id, (newId) => {
  if (newId) {
    groupTourId.value = newId
    loadRegistrations()
  }
}, { immediate: true })
</script>


<style scoped>
.group-tour-detail {
  padding: 0;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.post-container {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  background-color: #fff;
}
.post-container {
  flex: 1;
}
.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 10;
}

.post-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.header-actions .el-button {
  padding: 8px 16px;
  margin-left: 8px;
}

.post-content {
  padding: 0 24px 24px;
}

.upload-section {
  margin-bottom: 24px;
  padding-top: 16px;
}

.upload-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 15px;
  color: #333;
}

.upload-title .count {
  color: #999;
  font-size: 13px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 16px;
  margin-top: 20px;
  width: 100%;
}

.grid-item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 10px;
  min-height: 150px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px dashed #dcdfe6;
}

.grid-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 8px;
}


.two-column-form {
  display: flex;
  gap: 40px;
}

.two-column-form .column {
  flex: 1;
}

.inline-form {
  display: flex;
  align-items: center;
  gap: 40px;
}

.inline-form .el-form-item {
  margin-bottom: 0;
}

.recruitment-item {
  margin-left: 20px;
}

.delete-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  z-index: 2;
  opacity: 0.8;
}

.empty-placeholder {
  border-style: dashed;
  background-color: #fafafa;
}

.placeholder-icon {
  font-size: 24px;
  color: #909399;
  margin-bottom: 8px;
  cursor: pointer;
}

.plus-upload {
  display: contents;
}

.form-group {
  margin-bottom: 24px;
}

.title-input {
  font-size: 18px;
  font-weight: 600;
}

.title-input :deep(.el-input__inner) {
  border: none;
  padding: 0;
  height: auto;
  font-size: 18px;
  font-weight: 600;
}

.word-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.content-box {
  background: #fafafa;
  padding: 16px;
  border-radius: 8px;
}

.content-input
content-input :deep(.el-textarea__inner) {
border: 1px solid #eee;
padding: 12px;
resize: none;
box-shadow: none;
min-height: 150px;
background: #fff;
border-radius: 6px;
}

.info-card {
background-color: #fafafa;
border-radius: 12px;
padding: 16px;
margin-bottom: 16px;
}

.card-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}

.card-header h3 {
margin: 0;
font-size: 16px;
font-weight: 600;
}

.card-content {
padding-top: 8px;
}

:deep(.el-form-item) {
margin-bottom: 16px;
}

:deep(.el-form-item__label) {
color: #666;
font-weight: normal;
}

.dialog-content {
text-align: center;
padding: 20px 0;
}

.dialog-message {
margin-top: 20px;
font-size: 16px;
color: #333;
}

/* Rich Text Editor Styles */
.quill-editor {
  width: 100%;
  min-height: 320px;
  height: auto;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 12px;
  background: #f9f9f9;
  transition: box-shadow 0.3s ease;
  box-sizing: border-box;
}

.quill-editor:focus-within {
  box-shadow: 0 0 0 2px #409eff40;
}

.quill-editor :deep(.ql-toolbar) {
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  border-bottom: 1px solid #dcdfe6;
}

.quill-editor :deep(.ql-container) {
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
  min-height: 250px;
}

.quill-editor :deep(.ql-editor) {
  min-height: 250px;
  font-size: 14px;
  line-height: 1.6;
}

.registration-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}
</style>